package com.zero.client;

import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import com.zero.user.User;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ChatView extends JFrame {
	private static final long serialVersionUID = 2L;
	
	private User user; // 由客户端登录时设置
	private JTextArea textArea;
	private JTextField textFieldSendText;
	private JTextField textFieldSendTo;

	public ChatView(User user) {
		this.user = user;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		try {
			setIconImage(ImageIO.read(new File("res/Icon.jpg")));
		} catch (IOException e) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(null, "读取图标文件出错", "错误", JOptionPane.ERROR_MESSAGE));
		}
		setTitle("客户端" + user.getName());
		setSize(575, 410);

		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				int result = JOptionPane.showConfirmDialog(null, "确认退出？？？", "请确认", JOptionPane.OK_CANCEL_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					ClientSendThread.disconnect();
					System.exit(0);
				}
			}
		});

		init();
		setVisible(true); // 设置可见
	}

	private void init() {
		JLabel lblUser = new JLabel("用户：" + user.getNickname());
		lblUser.setFont(new Font("楷体", Font.BOLD, 15));
		lblUser.setHorizontalAlignment(SwingConstants.CENTER);

		JScrollPane scrollPane = new JScrollPane();

		textArea = new JTextArea();
		textArea.setEditable(false); // 设置为不可修改
		scrollPane.setViewportView(textArea);

		textFieldSendText = new JTextField();
		textFieldSendText.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					send();
				}
				if (e.getKeyChar() == KeyEvent.VK_RIGHT) {
					textFieldSendTo.grabFocus();
				}
			}
		});
		textFieldSendText.setFont(new Font("新宋体", Font.PLAIN, 18));

		JButton btnSend = new JButton("发送");
		btnSend.setFont(new Font("微软雅黑", Font.BOLD, 14));
		btnSend.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				send();
			}
		});

		textFieldSendTo = new JTextField();
		textFieldSendTo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					send();
				}
			}
		});
		textFieldSendTo.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 12));

		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,
				groupLayout.createSequentialGroup().addContainerGap().addGroup(groupLayout
						.createParallelGroup(Alignment.TRAILING)
						.addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)
						.addGroup(Alignment.LEADING,
								groupLayout.createSequentialGroup()
										.addComponent(textFieldSendText, GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
										.addGap(18).addComponent(btnSend, GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
										.addGap(18).addComponent(textFieldSendTo, GroupLayout.PREFERRED_SIZE, 70,
												GroupLayout.PREFERRED_SIZE))
						.addComponent(lblUser, GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)).addContainerGap()));
		groupLayout
				.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup().addContainerGap()
								.addComponent(lblUser, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE)
								.addGap(18).addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
								.addGap(18)
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
										.addComponent(textFieldSendText, GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
										.addGroup(groupLayout.createSequentialGroup().addGap(12)
												.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
														.addComponent(btnSend, GroupLayout.DEFAULT_SIZE, 28,
																Short.MAX_VALUE)
														.addComponent(textFieldSendTo))))
								.addGap(13)));
		getContentPane().setLayout(groupLayout);
	}

	/**
	 * 设置文本域
	 * 
	 * @param msg
	 */
	public void setTextArea(String msg) {
		textArea.append(msg + "\n");
		textArea.setCaretPosition(textArea.getDocument().getLength()); // 设置滚动条在最下面
	}

	/**
	 * 发送信息
	 */
	private void send() {
		String sendText = textFieldSendText.getText();
		String sendTo = textFieldSendTo.getText();
		// 文本框内容为空
		if (sendText.isEmpty()) {
			textFieldSendText.grabFocus();
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(this, "输入为空，请重新输入", "提示", JOptionPane.WARNING_MESSAGE));
			return;
		}
		try {
			if (sendTo.isBlank() || "all".equals(sendTo.toLowerCase())) {
				ClientSendThread.clientSendAll(sendText);
			} else {
				ClientSendThread.clientSend(sendText, sendTo);
			}
		} catch (UnsupportedEncodingException e) {
			SwingUtilities.invokeLater(() -> {
				int result = JOptionPane.showOptionDialog(this, "消息加密错误", "错误", JOptionPane.DEFAULT_OPTION,
						JOptionPane.ERROR_MESSAGE, null, null, null);
				if (result == JOptionPane.OK_OPTION || result == JOptionPane.CLOSED_OPTION) {
					System.exit(1);
				}
			});
		}
		textFieldSendText.setText(""); // 清空文本框
		textFieldSendTo.setText("");
		textFieldSendText.grabFocus(); // 设置焦点
	}
}
